package com.abc.recycling.controller.admin;

import com.abc.recycling.common.Result;
import com.abc.recycling.model.*;
import com.abc.recycling.service.UserService;
import com.abc.recycling.service.OrderService;
import com.abc.recycling.service.RecyclingStationService;
import com.abc.recycling.service.NotificationService;
import com.abc.recycling.service.NotificationTemplateService;
import com.abc.recycling.service.CollectorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;

@Slf4j
@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final OrderService orderService;
    private final UserService userService;
    private final RecyclingStationService stationService;
    private final NotificationService notificationService;
    private final CollectorService collectorService;

    @GetMapping({"", "/"})
    public String index() {
        return "redirect:/admin/dashboard";
    }

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // 获取统计数据
        model.addAttribute("todayOrders", orderService.countTodayOrders());
        model.addAttribute("activeUsers", userService.countActiveUsers());
        model.addAttribute("totalWeight", orderService.getTotalWeight());
        model.addAttribute("totalIncome", orderService.getTotalIncome());
        
        // 获取图表数据
        model.addAttribute("orderTrend", orderService.getOrderTrendData());
        model.addAttribute("itemDistribution", orderService.getItemDistributionData());
        
        // 获取最近订单
        model.addAttribute("recentOrders", orderService.getRecentOrders(10));
        
        return "admin/dashboard";
    }

    @GetMapping("/residents")
    public String getResidentsPage(Model model, @RequestParam(required = false) String keyword) {
        List<User> residents = userService.findResidents(keyword);
        model.addAttribute("residents", residents);
        model.addAttribute("keyword", keyword);
        return "admin/residents";
    }

    @GetMapping("/residents/{id}")
    @ResponseBody
    public User getResident(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping("/residents")
    @ResponseBody
    public ResponseEntity<?> createResident(@RequestBody User user) {
        user.setRole("RESIDENT");
        userService.create(user);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/residents/{id}")
    @ResponseBody
    public ResponseEntity<?> updateResident(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.update(user);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/residents/{id}/status")
    @ResponseBody
    public ResponseEntity<?> updateResidentStatus(@PathVariable Long id, @RequestParam Integer status) {
        userService.updateStatus(id, status);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/residents/{id}")
    @ResponseBody
    public ResponseEntity<?> deleteResident(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/collectors")
    public String collectors(@RequestParam(required = false) String keyword, Model model) {
        try {
            log.info("获取回收员列表, keyword={}", keyword);
            List<User> collectors = userService.findCollectors(keyword);
            model.addAttribute("collectors", collectors);
            model.addAttribute("keyword", keyword);
            return "admin/collectors";
        } catch (Exception e) {
            log.error("获取回收员列表失败: {}", e.getMessage());
            throw e;
        }
    }

    @GetMapping("/collectors/{id}")
    @ResponseBody
    public Result<User> getCollector(@PathVariable Long id) {
        try {
            log.info("获取回收员信息, id={}", id);
            User collector = userService.findById(id);
            log.debug("查询到的回收员信息: id={}, username={}, serviceArea={}, rating={}, monthlyOrders={}, totalOrders={}",
                collector.getId(), collector.getUsername(), collector.getServiceArea(),
                collector.getAverageRating(), collector.getMonthlyOrders(), collector.getTotalOrders());
            
            if (collector == null || !"COLLECTOR".equals(collector.getRole())) {
                log.warn("未找到回收员信息或角色不正确, id={}, role={}", 
                    id, collector != null ? collector.getRole() : null);
                return Result.error("未找到回收员信息");
            }
            
            return Result.success(collector);
        } catch (Exception e) {
            log.error("获取回收员信息失败: {}", e.getMessage(), e);
            return Result.error("获取回收员信息失败");
        }
    }

    @PostMapping("/collectors")
    @ResponseBody
    public ResponseEntity<?> createCollector(@RequestBody User user) {
        user.setRole("COLLECTOR");
        userService.create(user);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/collectors/{id}")
    @ResponseBody
    public ResponseEntity<?> updateCollector(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.update(user);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/collectors/{id}/status")
    @ResponseBody
    public ResponseEntity<?> updateCollectorStatus(@PathVariable Long id, @RequestParam Integer status) {
        userService.updateStatus(id, status);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/collectors/{id}")
    @ResponseBody
    public ResponseEntity<?> deleteCollector(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/collectors/{id}/details")
    public String getCollectorDetails(@PathVariable Long id, Model model) {
        User collector = userService.findById(id);
        model.addAttribute("collector", collector);
        
        // 获取回收员的订单统计数据
        model.addAttribute("orderStats", orderService.getCollectorOrderStats(id));
        
        // 获取回收员的最近订单
        model.addAttribute("recentOrders", orderService.findByCollectorId(id, PageRequest.of(0, 10)));
        
        return "admin/collector-details";
    }

    @GetMapping("/orders")
    public String orders(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            Model model) {
        try {
            log.debug("获取订单列表页面");
            return "admin/orders";
        } catch (Exception e) {
            log.error("获取订单列表页面失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    @GetMapping("/orders/data")
    @ResponseBody
    public Result<Page<Order>> getOrdersData(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page) {
        try {
            log.debug("获取订单列表数据, keyword={}, status={}, page={}", keyword, status, page);
            Page<Order> orderPage = orderService.findOrders(keyword, status, PageRequest.of(page, 10));
            return Result.success(orderPage);
        } catch (Exception e) {
            log.error("获取订单列表数据失败: {}", e.getMessage(), e);
            return Result.error("获取订单列表失败");
        }
    }

    @GetMapping("/orders/{id}")
    @ResponseBody
    public Order getOrder(@PathVariable Long id) {
        return orderService.findById(id);
    }

    @PostMapping("/orders/{id}/cancel")
    @ResponseBody
    public ResponseEntity<?> cancelOrder(@PathVariable Long id) {
        orderService.cancelOrder(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/export/orders")
    public void exportOrders(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletResponse response) throws IOException {
        
        // 处理日期参数
        LocalDateTime startTime = startDate != null ? 
            LocalDate.parse(startDate).atStartOfDay() : 
            LocalDateTime.now().minusMonths(1);
        LocalDateTime endTime = endDate != null ? 
            LocalDate.parse(endDate).plusDays(1).atStartOfDay() : 
            LocalDateTime.now();
        
        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("订单数据");
        
        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"订单编号", "用户", "回收员", "状态", "创建时间", "完成时间", "重量", "金额"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        
        // 获取订单数据
        List<Order> orders = orderService.getOrdersByDateRange(startTime, endTime);
        
        // 填充数据
        int rowNum = 1;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (Order order : orders) {
            Row row = sheet.createRow(rowNum++);
            
            // 订单编号
            row.createCell(0).setCellValue(order.getOrderNo());
            
            // 用户名
            User user = userService.findById(order.getUserId());
            row.createCell(1).setCellValue(user != null ? user.getUsername() : "未知");
            
            // 回收员
            User collector = order.getCollectorId() != null ? userService.findById(order.getCollectorId()) : null;
            row.createCell(2).setCellValue(collector != null ? collector.getUsername() : "未分配");
            
            // 状态
            row.createCell(3).setCellValue(order.getStatus());
            
            // 创建时间
            row.createCell(4).setCellValue(
                order.getCreateTime() != null ? order.getCreateTime().format(formatter) : ""
            );
            
            // 完成时间
            row.createCell(5).setCellValue(
                order.getCompleteTime() != null ? order.getCompleteTime().format(formatter) : ""
            );
            
            // 重量
            row.createCell(6).setCellValue(
                order.getActualWeight() != null ? order.getActualWeight() : 0.0
            );
            
            // 金额
            row.createCell(7).setCellValue(
                order.getPrice() != null ? order.getPrice().doubleValue() : 0.0
            );
        }
        
        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=orders.xlsx");
        
        // 写入响应
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    /**
     * 消息通知管理页面
     */
    @GetMapping("/notifications")
    public String getNotificationsPage() {
        return "admin/notifications";
    }

    /**
     * 获取系统消息列表
     */
    @GetMapping("/notifications/system")
    @ResponseBody
    public List<Notification> getSystemNotifications() {
        return notificationService.getSystemNotifications();
    }

    /**
     * 创建系统消息
     */
    @PostMapping("/notifications/system")
    @ResponseBody
    public ResponseEntity<?> createSystemNotification(@RequestBody Map<String, String> params) {
        try {
            notificationService.createSystemNotification(
                params.get("title"),
                params.get("content"),
                params.get("receiverType")
            );
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 发送消息
     */
    @PostMapping("/notifications/{id}/send")
    @ResponseBody
    public ResponseEntity<?> sendNotification(@PathVariable Long id) {
        try {
            notificationService.sendNotification(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/notifications/{id}")
    @ResponseBody
    public ResponseEntity<?> deleteNotification(@PathVariable Long id) {
        try {
            notificationService.deleteNotification(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 获取消息模板列表
     */
    @GetMapping("/notifications/templates")
    @ResponseBody
    public List<NotificationTemplate> getMessageTemplates() {
        return notificationService.getAllTemplates();
    }

    /**
     * 获取消息模板详情
     */
    @GetMapping("/notifications/templates/{id}")
    @ResponseBody
    public ResponseEntity<?> getMessageTemplate(@PathVariable Long id) {
        try {
            NotificationTemplate template = notificationService.getTemplateById(id);
            return ResponseEntity.ok(template);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 创建消息模板
     */
    @PostMapping("/notifications/templates")
    @ResponseBody
    public ResponseEntity<?> createMessageTemplate(@RequestBody NotificationTemplate template) {
        try {
            notificationService.createTemplate(template);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 更新消息模板
     */
    @PutMapping("/notifications/templates/{id}")
    @ResponseBody
    public ResponseEntity<?> updateMessageTemplate(@PathVariable Long id, @RequestBody NotificationTemplate template) {
        try {
            template.setId(id);
            notificationService.updateTemplate(template);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 更新模板状态
     */
    @PostMapping("/notifications/templates/{id}/status")
    @ResponseBody
    public ResponseEntity<?> updateTemplateStatus(@PathVariable Long id, @RequestBody Map<String, Integer> params) {
        try {
            notificationService.updateTemplateStatus(id, params.get("status"));
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 删除消息模板
     */
    @DeleteMapping("/notifications/templates/{id}")
    @ResponseBody
    public ResponseEntity<?> deleteMessageTemplate(@PathVariable Long id) {
        try {
            notificationService.deleteTemplate(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    private void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof Number) {
            cell.setCellValue(((Number) value).doubleValue());
        } else if (value instanceof LocalDateTime) {
            cell.setCellValue(((LocalDateTime) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else if (value instanceof Date) {
            cell.setCellValue((Date) value);
        } else {
            cell.setCellValue(String.valueOf(value));
        }
    }
} 